import React, { Component, lazy, Suspense } from 'react'
import './index.scss'
import { Redirect, Route, Switch } from 'react-router-dom'
import { Layout } from 'antd'

import Loading from '../../components/common/Loading'
import Err404 from '../../components/common/Err404'
import Leftnav from '../../components/content/Leftnav/Leftnav'
import Header from '../../components/content/Header/Header'

import routeConfig from './routeConfig'
import { connect } from 'react-redux'

const { Footer, Sider, Content } = Layout

class Admin extends Component {
    state = {
        hasError: '', //用于标识子组件是否产生错误
    }
    static getDerivedStateFromError(error) {
        console.log('@@@', error);
        return { hasError: error }
    }

    componentDidCatch() {
        console.log('此处统计错误，反馈给服务器，用于通知编码人员进行bug的解决');
    }
    render() {
        const user = this.props.user
        // 如果内存没有存储user ==> 当前没有登陆
        if (!user || !user.data) {
            // 自动跳转到登陆(在render()中)
            return <Redirect to='/login' />
        }
        return (
            <div id="admin">
                <Layout style={{ minHeight: '100%' }}>
                    <Sider className="left-nav">
                        <Leftnav></Leftnav>
                    </Sider>
                    <Layout style={{minHeight:'100vh'}}>
                        <Header />
                        <Content style={{ margin: 20, backgroundColor: '#fff' }} className="content">
                            {this.state.hasError ? <Err404 /> : <Suspense fallback={<Loading />}>
                                <Switch>
                                    <Redirect from='/' exact to="/home"></Redirect>
                                    <Route exact path={'/article'} component={lazy(() => import('./Article/Search'))}></Route>
                                    <Route exact path={'/product'} component={lazy(() => import('./Product/Product'))}></Route>
                                    {
                                        routeConfig.map((item)=>{//item.filePath+''转成字符串形式
                                        return <Route key={item.key} exact path={item.key} component={lazy(() => import(item.filePath+''))}></Route>})
                                    }
                                </Switch>
                            </Suspense>}
                        </Content>
                        <Footer style={{ textAlign: 'center', color: '#cccccc' }}>推荐使用谷歌浏览器，可以获得更佳页面操作体验</Footer>
                    </Layout>
                </Layout>
            </div>
        )
    }
}
export default connect(
    state=>({
        user: state.user
    }),
    {}
)(Admin)